package carcassonne.server.ioc;

import carcassonne.server.http.HttpContext;
import carcassonne.server.http.HttpParams;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MethodInfo {

    public Method Method;
    public List<String> RequiredKeys = new ArrayList<>();

    public MethodInfo(Method method, String params) {
        Method = method;
        if (params.length() > 0) {
            String[] strings = params.split(",");
            for (String s : strings) {
                RequiredKeys.add(s.trim());
            }
        }
    }

    public void Invoke(Object caller, HttpContext context, HttpParams params) {
        for (String key : RequiredKeys) {
            if (!params.Has(key)) {
                context.ResponseForbidden("param key <" + key + "> not found!");
                return;
            }
        }
        try {
            Method.invoke(caller, context, params);
        } catch (InvocationTargetException | IllegalAccessException e) {
            context.ResponseForbidden(e.getMessage());
        } catch (Exception e) {
            context.Response404();
        }
    }
}
